/*
 * Copyright (c) 2022. China Mobile (SuZhou) Software Technology Co.,Ltd. All rights reserved.
 * Lakehouse is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

import { abortJob } from '@/service/modules/sqlconsole'
import { SqlAbortResult } from '@/service/modules/sqlconsole/types'
import { useSqlExecTabStore } from '@/store/sqlconsole/sql-exec-tab'
import { SqlExec } from '@/store/sqlconsole/types'
import { NButton } from 'naive-ui'
import { defineComponent, h, inject, PropType } from 'vue'
import { useI18n } from 'vue-i18n'
import { SqlConsoleSymbol } from '..'
import useStatus from '../components/use-status'
import styles from './index.module.scss'

const props = {
  tab: {
    type: Object as PropType<SqlExec>,
    default: {}
  },
  bottomDivHeight: {
    type: Number
  }
}

const ExecResult = defineComponent({
  name: 'exec-result',
  props,
  setup(props, context) {
    const { t } = useI18n()

    const timerSet = inject(SqlConsoleSymbol, '')
    const { switchStatus } = useStatus()
    const $sqlExecTabStore = useSqlExecTabStore()

    const onAbortJob = (engineType: string) => {
      // remove timer
      timerSet.clearTimer(props.tab.jobId)
      abortJob(props.tab.jobId)
        .then((res: SqlAbortResult) => {
          if (res.sqlAbortResultItemDtos[0].commitSuccessed) {
            // change job status to cancel
            const _job = $sqlExecTabStore.getExecTabByJob(props.tab.jobId)

            $sqlExecTabStore.updateTab({
              ..._job,
              label: switchStatus('CANCELLED') + `(${props.tab.jobId})`,
              status: 'CANCELLED'
            })
          } else {
            timerSet.addTimer(props.tab.jobId, engineType, context)
          }
        })
        .catch(() => {
          // clear timer when execute failed
          timerSet.addTimer(props.tab.jobId, engineType, context)
        })
    }

    const showLog = () => {
      // TODO: add log modules
      const path = 'log'
      window.open(path, '_blank')
    }

    const renderFunc = (tab: any) => {
      switch (tab.stauts) {
        case 'ACCEPTED':
        case 'RUNNING':
        case 'SUBMITTED':
        case 'CANCELLED':
          return preparedComp(tab)
        case 'FINISHED':
          return finishedComp()
        case 'SUBMIT_FAILED':
          return submitFailedComp(tab)
        default:
          return defaultComp(tab)
      }
    }

    // ACCEPTED | RUNNING | SUBMITTED | CANCELLED
    const preparedComp = (tab: any) => {
      return [
        h(
          'div',
          { class: styles.title },
          {
            default: () => {
              return <span>{t('explore.exec_result_exec_tip')}</span>
            }
          }
        ),
        h(
          'div',
          { class: styles.abort },
          {
            default: () => {
              tab.status === 'CANCELLED' ? (
                <span>{t('explore.exec_result_abort_exec_tip')}</span>
              ) : (
                <NButton>{t('explore.exec_result_abort_tip')}</NButton>
              )
            }
          }
        ),
        h(
          'div',
          { class: styles.sql },
          {
            default: () => {
              return <span>{tab.sql}</span>
            }
          }
        )
      ]
    }

    // SUBMIT_FAILED
    const submitFailedComp = (tab: any) => {
      return [
        h(
          'span',
          {
            class: styles.title
          },
          {
            default: () => t('explore.exec_result_submit_failed')
          }
        ),
        h(
          'span',
          {
            class: styles.title
          },
          {
            default: () => {
              tab.sql
            }
          }
        ),
        h(
          'span',
          {},
          {
            default: () => {
              return t('explore.exec_result_failed_msg') + tab.errorMessage
            }
          }
        )
      ]
    }

    // FINISHED
    const finishedComp = () => {
      return h(
        'span',
        {},
        {
          default: () => 'success'
        }
      )
    }

    // DEFAULT
    const defaultComp = (tab: any) => {
      return [
        h(
          'div',
          {
            class: styles.title
          },
          {
            default: () => t('explore.exec_result_execution_failed')
          }
        ),
        h(
          'div',
          {
            class: styles.sql
          },
          {
            default: () => {
              if (tab.errorMessage) {
                return tab.errorMessage
              } else {
                return (
                  t('explore.exec_result_failed_msg') +
                  h(
                    'span',
                    { class: styles['show-log'] },
                    {
                      default: () => t('explore.exec_result_showlog')
                    }
                  )
                )
              }
            }
          }
        )
      ]
    }

    return { onAbortJob, showLog, renderFunc }
  },
  render() {
    return (
      <div class={styles.execResult}>
        <div class={styles.center}>{this.renderFunc(this.tab)}</div>
      </div>
    )
  }
})

export default ExecResult
